<template>
	<view style="height: 100%">
		<view class="previewBox" @tap="mpVid()" v-if="videoS">
			<swiper :indicator-dots="true" indicator-active-color='#FFF' indicator-color='rgba(255,255,255,0.3)'
				:duration="1000" style="width: 100%;height: 100vh;">
				<swiper-item v-for="(item, index) in mp" :key="index">
					<view style="height: 100vh;display: flex;align-items: center;">
						<video @click.stop="videoS=true" :src='item'></video>
					</view>
				</swiper-item>
			</swiper>
		</view>
		<view class="previewBox" @tap="hideSwiper()" v-if="showSwiper">
			<swiper :indicator-dots="true" :current="current" indicator-active-color='#FFF'
				indicator-color='rgba(255,255,255,0.3)' :duration="1000" style="width: 100%;height: 100vh;">
				<swiper-item v-for="(item, index) in img" :key="index">
					<view style="height: 100vh;display: flex;align-items: center;">
						<image referrerPolicy='no-referrer' mode="aspectFit" style="width: 750rpx;height: 100vh;"
							:src="item"></image>
					</view>
				</swiper-item>
			</swiper>
		</view>
		<view style="font-size: 26rpx;font-weight: bold;color:red;" v-if="userInfo.grade==1"> *会员可查看无水印图纸 </view>
		<block v-for="(item, index) in img" :key="index">
			<image class="img90 mr8 mt8" referrerPolicy='no-referrer' :src="item" @tap.stop.prevent="preview(index)"
				:data-src="item"></image>
		</block>
		<view class="">
		</view>
		<view class="pd150" v-if="name.length != 0">
			<view class="fileBox" v-for="(item, index) in name" :key="index">
				<view class="fileNum">
					{{index+1}}
				</view>
				<view class="file-box df ac sb">
					<image class="img16" src="https://wx.xtwaixie.com/img/file.png"></image>
					<p class="f14 c28 ml8 w224 ovh">{{ item }}</p>
					<p v-if="changeMp4(item)" class="f12 c10" :data-i="index">

						<view v-for="(items, index) in [file]">
							<p @click="videoMp(items)">在线预览</p>
						</view>
					</p>
					<p class="f12 c10" @tap.native="onLook($event, { i: index })" :data-i="index"
						v-else-if="changeBtn(item)">在线预览</p>
					<p class="f12 c10" @tap.native="onLook($event, { i: index })" :data-i="index" v-else>转发好友</p>
					<p class="f12 c10" style="opacity: 0;" v-else>在线预览</p>
				</view>
			</view>
			<view class="fileTips" v-if="isPc">
				<view class="tipTitle"> 复制文件链接，下载至电脑查看 </view>
				<view class="df">
					<!-- <view class="tipBtn" @tap="forward()"> 转发 </view> -->
					<view class="tipBtn" @tap="copy()"> 复制链接 </view>
				</view>
				<view class="tipContent"> 1.点击【复制链接】 </view>
				<view class="tipContent" style="margin-bottom: 20rpx;"> 2.在电脑端浏览器，粘贴链接即可下载 </view>
				<view class="tips" @click="lookMore()"> 查看详细步骤 </view>
			</view>
			<view v-else class="df" style="flex-direction: column;align-items: center;margin-top: 40rpx">
				<view class="tipBtn" @tap="sliderVerifyFLag = true">全部下载</view>
			</view>
		</view>
		<model :value='scancelAdmin' content='仅提供会员供应商下载' agreeBtn='升级会员' @change='scancelAdmin=false'
			@agree='confirmAdmin' />
		<van-popup :show="vipDetail" z-index='10000' :close-on-click-overlay='true'
			custom-style='background:rgba(0,0,0,0);' @close='close'>
			<view class="popupBox">
				<image referrerPolicy='no-referrer'
					src="https://cdn.xtwaixie.com/uploads/20231201/170141143665697a6c352bddrawing.png" mode="widthFix"
					class="popupImg" @click="member()" style="width: 610rpx;"></image>
			</view>
		</van-popup>
		<slider-verify :isShow="sliderVerifyFLag" @touchSliderResult="verifyResult" ref="verifyElement"></slider-verify>
		<van-popup :show="show" round>
			<p class="db pd200 mt5 w311">
				<span class="f16 c28 f500 db tc">确定下载？</span>
			</p>
			<view class="df ac btf1 h48">
				<p class="w50 tc f16 c28" @tap.native="show = false">取消</p>
				<button class="share-but1 h48 c10" @tap="forward">确定</button>
			</view>
		</van-popup>
	</view>
</template>
<script>
	// pages/demand/drawing.js
	const http = require('../../utils/http');
	import {
		model
	} from "@/component/model.vue"
	import sliderVerify from '@/component/slider-verify.vue'; //组件存放的路径
	export default {
		components: {
			model,
			sliderVerify
		},
		data() {
			return {
				show: false,
				name: [],
				file: [],
				lj_name: '',
				img: [],
				userInfo: {},
				platform: '',
				scancelAdmin: false,
				decrypt: '',
				decrypt_time: '',
				index: 0,
				userType: '',
				vipDetail: false,
				showSwiper: false,
				current: 0,
				id: 0,
				quotation: false,
				loading: false,
				img2: [],
				sliderVerifyFLag: false,
				isPc: false,
				videoS: false,
				mp: ""
			};
		}
		/**
		 * 生命周期函数--监听页面加载
		 */
		,
		onLoad(options) {
			uni.setStorageSync("platform", uni.getSystemInfoSync().platform);
			if (["windows", "mac"].some((v) => v == uni.getStorageSync("platform"))) {
				this.isPc = true
				console.log(this.isPC, 1111)
			}


			let obj = uni.getSystemInfoSync();
			this.platform = obj.platform
			this.quotation = options.quotation == 1
			console.log(options)
			let userInfo=uni.getStorageSync('userInfo')
			// console.log(userInfo)
			this.setData({
				name: JSON.parse(options.name) ? JSON.parse(options.name) : [],
				file: JSON.parse(options.file),
				lj_name: options.lj_name,
				img: JSON.parse(options.img).map(item => {
					// if (!options.grade && !this.quotation) {
					// 	item = item + this.shuiyin
					// }
					// vip没有水印,优选供应商有水印
					if (userInfo?.grade&&userInfo?.grade != 2) {
						item = item + this.shuiyin
					}
					return item
				}),
				img2: JSON.parse(options.img)
			});
			if (options.index) {
				this.index = options.index
			}
			if (options.userType) {
				this.userType = options.userType
			}
			this.decrypt = decodeURIComponent(options.decrypt)
			this.decrypt_time = options.decrypt_time
			this.id = options.id
			console.log(options);
			uni.setNavigationBarTitle({
				title: this.quotation ? '报价附件' : options.lj_name
			});
			this.getUserInfo();
			http.request('demand/getIp', {
				type: 0,
				id: options.id
			}).then((res) => {}).catch((res) => {
				console.log(res);
			});
		},
		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady() {},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow() {},
		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide() {},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload() {},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh() {},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom() {},
		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage() {},
		methods: {
			videoMp(Mp) {
				console.log(Mp)
				let typeList = ['mp4']
				this.mp = Mp.filter(item => item.includes(typeList))
				console.log(this.mp)
				this.videoS = true
			},
			copylink() {
				uni.setClipboardData({
					data: 'https://www.666xpkj.com/',
					success: function() {
						return uni.showToast({
							icon: "none",
							title: '复制链接成功，去分享给你的好友吧!',
						});
					}
				});
			},
			close() {
				this.vipDetail = false
			},
			hideSwiper() {
				this.showSwiper = false
			},
			mpVid() {
				this.videoS = false
			},
			member() {
				this.vipDetail = false
				uni.navigateTo({
					url: '/pages/recharge/recharge'
				});
				// if (this.platform === 'ios') {
				// 	uni.navigateTo({
				// 		url: '/pages/recharge/iosvip'
				// 	});
				// } else {
				// 	uni.navigateTo({
				// 		url: '/pages/recharge/recharge'
				// 	});
				// }
			},
			changeBtn(item) {
				let typeList = ['doc', 'xls', 'ppt', 'pdf', 'PDF', 'docx', 'xlsx', 'pptx']
				let result = false
				typeList.forEach((res) => {
					if (item.split('.')[item.split('.').length - 1] == res) {
						result = true
					}
				})
				return result
			},
			changeMp4(item) {

				let typeList = ['mp4']
				let result = false
				typeList.forEach((res) => {
					if (item.split('.')[item.split('.').length - 1] == res) {
						result = true
					}
				})
				return result
			},
			preview(index) {
				// this.current = index
				// this.showSwiper = true
				const url = this.img[index]
				const img = this.img.map(item => {
					return item
				})
				// let curr = event.target.dataset.curr;
				console.log(url, "img")
				uni.previewImage({
					current: url,
					// 当前显示图片的http链接
					// referrerPolicy: "no-referrer",
					urls: img // 需要预览的图片http链接列表
				});
			},
			confirmAdmin() {
				this.scancelAdmin = false
				uni.navigateTo({
					url: '/pages/recharge/recharge'
				});
				// if (this.platform == 'ios') {
				// 	uni.navigateTo({
				// 		url: '/pages/recharge/iosvip'
				// 	});
				// } else {
				// 	uni.navigateTo({
				// 		url: '/pages/recharge/recharge'
				// 	});
				// }
			},
			onLook(e, _dataset) {
				if (this.loading) {
					return
				}
				this.loading = true
				setTimeout(() => {
					this.loading = false
				}, 1000);
				/* ---处理dataset begin--- */
				this.handleDataset(e, _dataset);
				/* ---处理dataset end--- */
				let i = e.currentTarget.dataset.i;
				let url = this.file[i];
				const status = this.changeBtn(url)
				const extension = this.getFileExtension(url);
				const randfile = this.name[i].endsWith('.' + extension) ? this.name[i] : this.name[i] + '.' + extension
				const newPath = `${wx.env.USER_DATA_PATH}/${randfile}`;
				let showMenu = this.userInfo.grade == 2;
				uni.showLoading({
					title: '文件下载中'
				});
				uni.downloadFile({
					url: url,
					filePath: newPath,
					success(res) {
						console.log(res);
						if (res.statusCode === 200) {
							if (status) {
								uni.openDocument({
									filePath: res.filePath || res.tempFilePath,
									showMenu: showMenu,
									success(res) {
										// console.log(res);
										console.log('打开/文档成功');
										uni.hideLoading();
									},
									fail(res) {
										console.log(res);
										uni.hideLoading();
									}
								});
							} else {
								uni.shareFileMessage({
									filePath: res.filePath || res.tempFilePath,
									success(res) {
										// console.log(res);
										uni.hideLoading();
									},
									fail(res) {
										console.log(res);
										uni.hideLoading();
									}
								});
							}
						} else {
							uni.hideLoading();
						}
					},
					fail(res) {
						console.log(res);
						uni.hideLoading();
					}
				});
			},
			getFileExtension(filePath) {
				// 使用最后一个点和文件名的分隔符来获取文件名
				const filename = filePath.split('/').pop();
				// 获取文件名中的后缀部分
				const extension = filename.split('.').pop();
				return extension;
			},
			lookMore() {
				uni.navigateTo({
					url: '/subPack/step/step'
				})
			},
			copy() {
				http.request('demand/getIp', {
					type: 1,
					id: this.id,
					name: this.lj_name,
					file: this.file || [],
					fileName: this.name || [],
					img: this.img2 || [],
				}).then((res) => {
					const url = res.data.url
					uni.setClipboardData({
						data: http.url + url,
						success(res) {
							uni.showToast({
								title: '复制成功',
								icon: 'none'
							});
						},
						fail(err) {
							console.log(err);
						}
					});
				}).catch((res) => {
					console.log(res);
					uni.hideLoading();
				});
				// http.request('demand/getIp', {
				// 	type: 1,
				// 	id: this.id,
				// }).then((res) => {
				// 	let text = http.url +
				// 		`/h5/?#/?decrypt=${this.decrypt}${this.index == 1 ? '&index=1':''}&decrypt_time=${this.decrypt_time}`
				// 	uni.setClipboardData({
				// 		data: text,
				// 		success(res) {
				// 			uni.showToast({
				// 				title: '复制成功',
				// 				icon: 'none'
				// 			});
				// 		},
				// 		fail(err) {
				// 			console.log(err);
				// 		}
				// 	});
				// }).catch((res) => {
				// 	console.log(res);
				// });
			},
			verifyResult(res) {
				this.sliderVerifyFLag = false;
				if (res) { //校验通过
					this.show = true
				}
			},
			forward() {
				if (this.loading) {
					return
				}
				this.show = false
				this.loading = true
				uni.showLoading({
					title: '文件下载中'
				});
				setTimeout(() => {
					this.loading = false
				}, 1000);
				if (this.file.length + this.img.length === 1) {
					let url = '';
					let filePath = ''
					if (this.file.length > 0) {
						url = this.file[0]
						const extension = this.getFileExtension(url);
						const randfile = this.name[0].endsWith('.' + extension) ? this.name[0] : this.name[0] + '.' +
							extension
						filePath = `${wx.env.USER_DATA_PATH}/${randfile}`;
					} else {
						url = this.img2[0]
						filePath = wx.env.USER_DATA_PATH + this.img2[0].substring(this.img2[0].lastIndexOf('/'));
					}

					uni.downloadFile({
						url: url,
						filePath,
						success(res) {
							if (res.statusCode === 200) {
								uni.shareFileMessage({
									filePath: res.filePath || res.tempFilePath,
									success(res) {
										// console.log(res);
										uni.hideLoading();
									},
									fail(res) {
										uni.showToast({
											title: '分享失败1',
											icon: 'none'
										});
										uni.hideLoading();
									}
								});
							} else {
								uni.showToast({
									title: '分享失败2',
									icon: 'none'
								});
								uni.hideLoading();
							}
						},
						fail(res) {
							uni.showToast({
								title: '分享失败3',
								icon: 'none'
							});
							uni.hideLoading();
						}
					})
					return
				}
				http.request('demand/getIp', {
					type: 1,
					id: this.id,
					name: this.lj_name,
					file: this.file || [],
					fileName: this.name || [],
					img: this.img2 || [],
				}).then((res) => {
					const url = res.data.url
					uni.downloadFile({
						url: http.url + url,
						filePath: wx.env.USER_DATA_PATH + url.substring(url.lastIndexOf('/')),
						success(res) {
							if (res.statusCode === 200) {
								wx.shareFileMessage({
									filePath: res.filePath || res.tempFilePath,
									success(res) {
										console.log(res);
										http.request('demand/unlink', {
											url
										})
										uni.hideLoading();
									},
									fail(res) {
										console.log(res);
										http.request('demand/unlink', {
											url
										})
										uni.showToast({
											title: '分享失败4',
											icon: 'none'
										});
										uni.hideLoading();
									}
								});
							} else {
								http.request('demand/unlink', {
									url
								})
								uni.showToast({
									title: '分享失败5',
									icon: 'none'
								});
								uni.hideLoading();
							}
						},
						fail(res) {
							console.log(res)
							http.request('demand/unlink', {
								url
							})
							uni.showToast({
								title: '分享失败6',
								icon: 'none'
							});
							uni.hideLoading();
						}
					})
				}).catch((res) => {
					console.log(res);
					uni.hideLoading();
				});
			},
			getUserInfo() {
				http.request('user/userInfo').then((res) => {
					this.setData({
						userInfo: res.data.userInfo
					});
				}).catch((res) => {
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
				});
			}
		}
	};
</script>
<style>
	@import './drawing.css';

	.videoTz {
		position: fixed;
		top: 0;
		background: #283043;
		width: 100%;
		height: 100%;
	}

	.videoTz-info {
		position: absolute;
		top: 50%;
		transform: translateY(-50%);
		width: 100%;
	}

	video {
		width: 100%;
	}

	.previewBox {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		background-color: rgba(0, 0, 0, 0.9);
	}

	.fileBox {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.fileNum {
		color: #9DA3B0;
	}

	.fileTips {
		padding: 20rpx 0;
		margin-top: 20rpx;
		background-color: #f7f8fc;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.tipTitle {
		color: #283043;
		font-size: 28rpx;
		margin-bottom: 20rpx;
	}

	.tipContent {
		color: #9DA3B0;
		font-size: 24rpx;
	}

	.tipBtn {
		background-color: #68BF7B;
		width: 300rpx;
		border-radius: 16rpx;
		font-size: 28rpx;
		color: #FFF;
		text-align: center;
		line-height: 70rpx;
		font-weight: bold;
		margin: 0 20rpx 20rpx;
	}

	.tips {
		color: #1050c7;
		font-size: 24rpx;
		text-decoration: underline;
	}

	.share-but1 {
		width: 50% !important;
		font-size: 32rpx;
		padding: 0 !important;
		margin: 0 !important;
		font-weight: 400;
		text-align: center;
		color: #283043;
		line-height: 96rpx;
		border-left: 1rpx solid #ebedf0;
	}
</style>